package com.tanhua.dubbo.api;

import com.tanhua.model.domain.mongo.Friend;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.List;

/**
 * @author lk
 * @date 2022-03-31
 */
@DubboService
public class FriendApiImpl implements FriendApi {
    @Autowired
    private MongoTemplate mongoTemplate;

    //添加好友关系
    @Override
    public void save(Long friendId, Long userId) {
        //保存自己的好友数据
        Query query1 = Query.query(Criteria.where("friendId").is(friendId).and("userId").is(userId));
        //判断好友关系是否存在
        boolean exists1 = mongoTemplate.exists(query1, Friend.class);
        if (!exists1){
            // 如果不存在，保存
            Friend friend1 = new Friend();
            friend1.setFriendId(friendId);
            friend1.setUserId(userId);
            friend1.setCreated(System.currentTimeMillis());
            mongoTemplate.save(friend1);
        }

        //保存好友的数据
        Query query2 = Query.query(Criteria.where("friendId").is(userId).and("userId").is(friendId));
        //判断好友关系是否存在
        boolean exists2 = mongoTemplate.exists(query1, Friend.class);
        if (!exists2){
            // 如果不存在，保存
            Friend friend2 = new Friend();
            friend2.setFriendId(userId);
            friend2.setUserId(friendId);
            friend2.setCreated(System.currentTimeMillis());
            mongoTemplate.save(friend2);
        }
    }


    //分页查询联系人列表
    @Override
    public List<Friend> findByUserId(Long userId, Integer page, Integer pagesize) {
        //创建分页条件
        Query query = Query.query(Criteria.where("userId").is(userId))
                .skip((page-1)*pagesize).limit(pagesize);
        List<Friend> list = mongoTemplate.find(query, Friend.class);
        return list;
    }
}
